﻿<%@ WebHandler Language="C#" Class="requestDataTable" %>

using System;
using System.Web;
using System.Data;
using System.Text;
using System.Data.SqlClient;

public class requestDataTable : AjaxHandlerBase
{
    
    override public void RequestProcess(HttpContext context) {
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";
        
        string strOp = context.Request["op"];
        string strResponse = "";
        switch (strOp.ToLower())
        {
            case "getlist":
                strResponse = search(context);
                break;
            default:
                break;
        }
        context.Response.Write(strResponse);
    }
    
    
    //*******************************************
    //功能概要       ：获得请求列表
    //参数説明       ：请求列表
    //返回值説明     ：void
    //功能詳細       ：获得请求列表
    //作成者         ：chen.yugong 
    //作成日         ：2010-03-02
    //修改者         ：
    //修改日         ：
    //*******************************************
    private string search(HttpContext context)
    {
        try
        {
            int iPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;//页码
            int iPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 30 : int.Parse(context.Request["pagesize"]);//页记录数

            string fieldlist = "RecordId,RequestUser,ChangeType,Remarks,HouseAddress,Status";
            string fieldtablelist = "RecordId,RequestUser,CASE ChangeType when '10'  then '变更状态' when '20' then '变更所属人' when '30' then '两者都变更' end as ChangeType,Remarks,HouseAddress,CASE Status when '0'  then '处理中' when '1' then '处理完成' when '-1' then '请求被否决' end as Status";
            string orderfield = "House_RequestChangeInfo.Addtime desc";

            Guid cityId = (string.IsNullOrEmpty(context.Request["cityid"])) ? CurrentUserInfo.CityId : new Guid(context.Request["cityid"]);
            Guid companyId = (string.IsNullOrEmpty(context.Request["companyid"])) ? CurrentUserInfo.CompanyId : new Guid(context.Request["companyid"]);
            Guid areaId = (string.IsNullOrEmpty(context.Request["areaid"])) ? Guid.Empty : new Guid(context.Request["areaId"]);
            Guid departId = (string.IsNullOrEmpty(context.Request["departid"])) ? Guid.Empty : new Guid(context.Request["departid"]);
            Guid userId = (string.IsNullOrEmpty(context.Request["userid"])) ? Guid.Empty : new Guid(context.Request["userid"]);
          
            //判断权限范围/////////////////////////////////////////////
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            if (userId != Guid.Empty)
                sb.AppendFormat(" AND (RequestUserId = '{0}') ", userId);
            else if (departId != Guid.Empty)
                sb.AppendFormat(" AND (RequestDepart = '{0}')", departId);
            else if (areaId != Guid.Empty)
            {
                Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo item = null;
                string strCachkey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT, areaId);
                Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                item = cs.GetObject<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>(strCachkey);
                if (!cs.Hit)
                {
                    item = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(areaId);
                    if (item != null) cs.Set(strCachkey, item, DateTime.Now.AddDays(1));
                }

                if (item == null) return string.Format("{{success:'0',msg:'{0}',data:''}}", "获取商圈或分类数据丢失");

                sb.AppendFormat(" AND (RequestDepart in (select departId from v_Hr_DepartmentInfo where DepartSrc like '{0}%'))", item.DepartSrc);
            }
            else if (companyId != Guid.Empty)
                sb.AppendFormat(" AND  CompanyId = '{0}' ", companyId);
            else if (cityId != Guid.Empty)
                sb.AppendFormat(" AND (RequestDepart in (Select DepartId from v_Hr_DepartmentInfo where CityId = '{0}'))", cityId);

            /*
            string strPermitCode0 = "house.view.all.open";//查看所有非隐藏房源权限
            System.Text.StringBuilder sb1 = new System.Text.StringBuilder();
            if (CurrentUserInfo.ContainsPermit(strPermitCode0))
            {
                sb1.Append(" (1=1) ");
            }
            else
            {
                sb1.Append("(EXISTS(");
                sb1.Append("Select 1 from v_Struct_UserDepartRelation M ");
                sb1.AppendFormat("WHERE (House_BaseInfo.OprDepartId = M.Departid AND  M.Userid= '{0}') ", CurrentUserInfo.UserId);
                sb1.Append("AND ((House_BaseInfo.IsProtectHouse = 1 AND M.ViewPrivHouse =1) OR ");
                sb1.Append("(House_BaseInfo.IsProtectHouse = 0 AND M.ViewPubHouse =1))");
                sb1.Append("))");
            }*/
            System.Text.StringBuilder sb1 = new System.Text.StringBuilder();
            sb1.Append(" (1=1) ");
            if (!String.IsNullOrEmpty(sb.ToString()))
                sb1.Append(sb.ToString());

            string stime = context.Request.QueryString["stime"];
            string etime = context.Request.QueryString["etime"];
            string strquery = context.Request.QueryString["strquery"];
            string requeststatus = context.Request.QueryString["requeststatus"];
            if (!String.IsNullOrEmpty(stime))
            {
                sb1.Append(string.Format(" AND convert(varchar(10),(convert(datetime,Addtime,120)),120)  >= '{0}'", (stime)));
            }
            if (!String.IsNullOrEmpty(etime))
            {
                sb1.Append(string.Format(" AND convert(varchar(10),(convert(datetime,Addtime,120)),120)  <= '{0}'", (etime)));
            }
            if (!String.IsNullOrEmpty(strquery))
            {
                sb1.Append("AND HouseAddress LIKE '%" + strquery + "%'");
            }
            if (!String.IsNullOrEmpty(requeststatus))
            {
                sb1.Append(string.Format(" and Status= '{0}'", requeststatus));
            }
            
            
            
            //判断权限范围结束////////////////////////////////////////////


            System.Data.DataSet list = null;
            list = Chenxin.Lib.House.DAL.House_RequestChangeInfo.GetList(
                iPageIndex, iPageSize, orderfield, "House_RequestChangeInfo", sb1.ToString(), fieldlist, fieldtablelist, true);
            int count = (int)list.Tables[1].Rows[0][0];
            string strHtml = "";
            if (!GetKeyListHtml(list, out strHtml))
            {
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "生成HTML错误:" + strHtml);
            }
            list.Dispose();
            list = null;
            return string.Format("{{success:'1',msg:'{0}',data:{{count:'{1}',data:'{2}'}}}}", "成功", count, strHtml);
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message);
        }
    }

    /// <summary>
    /// 返回列表；
    /// 根据查询参数生成查询条件1,根据权限设定生成查询条件2；
    /// 返回Json数据：{count:'30',data:'abc'}
    /// </summary>
    /// <param name="context"></param>
    private bool GetKeyListHtml(System.Data.DataSet dslist, out string strHtml)
    {
        try
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("<table width=\"100%\" height=\"100%\" cellspacing=\"1\" class=\"tabsorternew\" id=\"report\">");
            sb.Append("<thead><tr>");
            sb.Append("<th width=\"38\">操作</th>");
            sb.Append("<th width=\"38\">请求人</th>");
            sb.Append("<th width=\"35\" >变更类型</th>");
            sb.Append("<th width=\"35\" >变更理由</th>");
            sb.Append("<th width=\"150\">房源地址</th>");
            sb.Append("<th width=\"40\">处理状态</th>");
            sb.Append("</tr></thead><tbody>");
            foreach (System.Data.DataRow row in dslist.Tables[0].Rows)
            {
                string button = string.Format("<a name=\"{0}\" href=\"#\" class=\"a_favor_remove\">审核</a>", row["RecordId"]) + "   " + string.Format("<a name=\"{0}\" href=\"#\" class=\"a_favor_remove\">详细</a>", row["RecordId"]);
                sb.AppendFormat("<tr id=\"{0}\" class=\"tr_houselist\">", row["RecordId"].ToString());
                sb.AppendFormat("<td>{0}</td>",button);
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "RequestUser", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ChangeType", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Remarks", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "HouseAddress", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Status", ""));
                sb.Append("</tr>");
            }

            sb.Append("</tbody></table>");
            strHtml = sb.ToString();
            return true;
        }
        catch (Exception ex)
        {
            strHtml = ex.Message;
            return false;
        }
    }


    public bool IsReusable {
        get {
            return false;
        }
    }
}